package com.project.framework.interceptor;

import com.project.client.domain.UserEntity;
import com.project.client.service.UserService;
import com.project.common.constant.Constants;
import com.project.common.constant.HttpStatus;
import com.project.common.core.domain.model.LoginClientUser;
import com.project.common.exception.CustomException;
import com.project.framework.annotation.PersonalLogin;
import com.project.framework.web.service.ClientTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 个人用户登录拦截器
 */
@Component
public class PersonalAuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private ClientTokenService tokenService;

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        PersonalLogin annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(PersonalLogin.class);
        } else {
            return true;
        }
        if (annotation == null) {
            return true;
        }
        LoginClientUser loginUser = tokenService.getLoginUser(request);
        if (loginUser == null) {
            String token = tokenService.getToken(request);
            if (StringUtils.isEmpty(token)) {
                throw new CustomException("请登录后操作", HttpStatus.UNAUTHORIZED);
            } else {
                throw new CustomException("登录信息异常", HttpStatus.FORBIDDEN);
            }
        }
        tokenService.verifyToken(loginUser);

        UserEntity user = userService.selectById(loginUser.getUid());
        if (user == null) {
            throw new CustomException("登录信息异常", HttpStatus.FORBIDDEN);
        }
        request.setAttribute(Constants.LOGIN_CLIENT_USER_KEY, user);
        return super.preHandle(request, response, handler);
    }
}
